package com.itheima.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.utils.JwtUtils;
import com.itheima.utils.TliasException;
import com.itheima.mapper.EmpExprMapper;
import com.itheima.mapper.EmpMapper;
import com.itheima.pojo.*;
import com.itheima.service.EmpLogService;
import com.itheima.service.EmpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class EmpServiceImpl implements EmpService {

    @Autowired
    private EmpMapper empMapper;
    @Autowired
    private EmpExprMapper empExprMapper;
    @Autowired
    private EmpLogService empLogService;

    @Override
    public PageResult page(EmpQueryParam e) {

        //在查询前调用startPage
        PageHelper.startPage(e.getPage(), e.getPageSize());
        //执行查询,此时Mybatis返回的List已经是物理分页后的结果,mapper层
        List<Emp> empList = empMapper.list(e);
        // 封装分页结果
        Page<Emp> p = (Page<Emp>) empList;
        //p.getTotal(),p.getResult()比较难想到
        return new PageResult(p.getTotal(), p.getResult());
    }

    //2.2 删除员工
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteEmployee(List<Integer> empIds) {
        empMapper.deleteEmployee(empIds);

        //2.根据员工的ID批量删除员工的工作经历信息
        empExprMapper.deleteEmployeeWorkExperience(empIds);

    }


    //(rollbackFor = Exception.class)事务出现任何异常都回滚
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void addEmployee(Emp emp) {


        try {
            //补全基础属性
            emp.setCreateTime(LocalDateTime.now());
            emp.setUpdateTime(LocalDateTime.now());
            empMapper.addEmployee(emp);


            //记录操作日志
            EmpLog empLog = new EmpLog(null, LocalDateTime.now(), emp.toString());
            empLogService.insertLog(empLog);

            //3.保存员工的工作经历信息 -批量
            Integer empId = emp.getId();
            List<EmpExpr> exprList = emp.getExprList();

            //检查工作经历列表是否为空
            if (!CollectionUtils.isEmpty(exprList)){

                //遍历exprList中的每一个EmpEXpr对象,并为他们设置empId的属性
                 exprList.forEach(empExpr -> empExpr.setEmpId(empId));

                 //将整个工作经历列表插入到数据库中
                 empExprMapper.insertEmployeeWorkExperienceTable(exprList);
            }
        } finally {

        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Emp findById( Integer id) {
        Emp emp = empMapper.findById(id);
        //记录操作日志
        EmpLog empLog = new EmpLog(null, LocalDateTime.now(), emp.toString());
        empLogService.insertLog(empLog);

        List<EmpExpr> workExperienceById = empExprMapper.getWorkExperienceById(id);
        emp.setExprList(workExperienceById);
        return emp;
    }

    //修改员工
    @Override
    public void modifyEmployee(Emp emp) {
        List<EmpExpr> empExprList = emp.getExprList();
        empExprMapper.modifyEmployeeWorkExperienceInfo(empExprList);
        emp.setUpdateTime(LocalDateTime.now());
        empMapper.modifyEmployee(emp);
    }

    @Override
    public List<Emp> queryAllEmployees() {
        return empMapper.queryAllEmployees();
    }

    @Override
    public LoginInfo login(Emp empDto) throws TliasException {
        // 根据用户名和密码查询emp  最多查到一个
        Emp emp =  empMapper.findEmpByUsernameAndPassword(empDto.getUsername(),empDto.getPassword());

        // 如果没有查到 用户名或密码错误
        if(emp==null){
            throw new TliasException("用户名或密码错误");
        }

        // 创建JWT token
        Map<String, Object> claims = new HashMap<>();
        claims.put("id", emp.getId());
        claims.put("username", emp.getUsername());
        claims.put("name", emp.getName());
        String token = JwtUtils.generateJwt(claims);

        LoginInfo loginInfo = new LoginInfo();
        loginInfo.setId(emp.getId());
        loginInfo.setName(emp.getName());
        loginInfo.setUsername(emp.getUsername());
        loginInfo.setToken(token); // 设置token
        return loginInfo;
    }
}